SpringBoot+Mybatis实现分页查询[通俗易懂] | 您所在的位置:网站首页 › springboot 分页查询参数 › SpringBoot+Mybatis实现分页查询[通俗易懂] |
大家好,又见面了,我是你们的朋友全栈君。 文章目录前言1.引入依赖2.Mapper中接口3.修改XML文件4.controller层调用接口5.测试总结前言分页查询是在web开发中常用的一种技术,当某个页面查询返回的数据量较大时,为了提高性能和用户体验不能将所有数据一次性返回给过前端,这时候就需要用到分页查询了 PageHelper是一款开源的Mybatis第三方物理分页插件,spring boot项目中集成PageHelper插件非常简单,下面将为大家详细介绍; 插件地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md 1.引入依赖在上一篇文章Mybatis 实现基本的增删改查 (基于Mybatis-generator插件方式)的基础上,在pom.xml中添加如下依赖: com.github.pagehelper pagehelper-spring-boot-starter 1.2.3 2.Mapper中接口在EmployeeMapper.java中新增findByPaging接口,接口返回类型为Page public interface EmployeeMapper { int deleteByPrimaryKey(Long id); int insert(Employee record); int insertSelective(Employee record); Employee selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Employee record); int updateByPrimaryKey(Employee record); Page findByPaging(Map param); }3.修改XML文件在EmployeeMapper.xml中添加上面接口对应Sql查询语句,可以看到使用插件的方式查询时,这里入参的类型为com.github.pagehelper.Page select * from employee where 1=1 and age = #{age} 4.controller层调用接口EmployeeController.java中新增findBypaging方法 @ApiOperation(value = "分页查询") @GetMapping("findBypaging") public ResultMsg findByPaging(Integer age,Integer pageNum, Integer pageSize){ PageHelper.startPage(pageNum,pageSize); Map param = new HashMap(); param.put("age",age); Page data = employeeMapper.findByPaging(param); JSONObject result = new JSONObject(); result.put("employees",data); result.put("pages",data.getPages()); result.put("total",data.getTotal()); return ResultMsg.getMsg(result); }ps:这里分页查询参数的传递方式和普通的查询是一样的,map的方式添加就可以了 5.测试编写一个测试用例,向数据库中批量插入200个员工数据 @RunWith(SpringRunner.class) @SpringBootTest public class HrefApplicationTests { @Autowired private EmployeeMapper employeeMapper; @Autowired private IdWorker idWorker; public static String getRandomStr(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; int randomNum; char randomChar; Random random = new Random(); // StringBuffer类型的可以append增加字符 StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { // 可生成[0,n)之间的整数,获得随机位置 randomNum = random.nextInt(base.length()); // 获得随机位置对应的字符 randomChar = base.charAt(randomNum); // 组成一个随机字符串 str.append(randomChar); } return str.toString(); } Employee createRadomEmployee() { Employee employee = new Employee(); employee.setAddress("北新街" + getRandomStr(5)); employee.setAge("22"); employee.setGender(new Short("1")); employee.setCreateTime(new Date()); employee.setName(getRandomStr(10)); employee.setId(idWorker.nextId()); return employee; } @Test public void insertEmployees() { for(int i=0;i |
CopyRight 2018-2019 实验室设备网 版权所有 |